var addFlag=true;
var updateFlag=true;
var menu = {
        
    menuTreeIds:"",
    menuData:[],
    menuEditData:[],
    menuCode:[],
    menuCategoryClass:"menuState",
     
    init : function() {
        //初始化按钮
        setMenuButtonOpermission();
    
        // 初始化下拉树控件
        menu.refreshCombotree();
        // 初始化菜单状态下拉框
        menu.initStateCombobox();
        // 加载表单数据
        menu.loadData();
        // 初始化事件绑定
        menu.evenBind();
        
    },
    //初始化菜单状态下拉框
    initStateCombobox:function(){
       
        $('#searchMenuState').combobox({
            url : getProjectUrl('/bfs/configuration/categorylist?type=0&categoryclass='+menu.menuCategoryClass),
            valueField : 'generalCode',
            textField : 'categoryName',
            onLoadSuccess : function() { // 加载完成后,设置选中第一项
                $(this).combobox('select', "");
            }
        });
        
    },
    evenBind : function() {
       
        // ----------------------------------------------------------------------->
        // 初始化
        // ----------------------------------------------------------------------->
        //折叠
        $('#collapseAllDept').bind("click", function() {
            $("#listDataEx1").treegrid("collapseAll");
        });
        
        $("#btnSearch").bind("click", function() {
            $("#listDataEx1").treegrid("unselectAll");
            menu.loadData();
        });
        // ----------------------------------------------------------------------->
        // 添加
        // ----------------------------------------------------------------------->
        $('#add').bind('click', function() {
            $('#createMenuForm').form('clear');
            $('#createMenuForm').form('load', {
                mstatus : "1"
            });
            $('input[name=mstatus]').get(1).checked = true;
            $('#createMenuDiv').window({
                onOpen : function() {
                    menu.refreshMenuCodeCombobox();
                }
            });
            $('#createMenuDiv').window('open');
        });
        
        // 取消
        $('#cancelCreateMenu').bind('click', function() {
            $('#createMenuDiv').window('close');
            $('#createMenuForm').form('clear');
        });

        // 提交
        $('#submitCreateMenu').bind('click', function() {
        	if(addFlag){
        		addFlag=false;
        		$('#createMenuForm').form('submit', {
                    url : getProjectUrl('/bfs/menu/add'),
                    onSubmit : function() {
                    	addFlag=true;
                        var validSuccess = $(this).form('validate');
                        if (!validSuccess) {
                            return false;
                        }
                        var addMenuName = $('#addMenuName').val();
                        var addMenuCode=$('#addMenuCode').combobox('getValue');
                        var _valid = menu.validMenuName(null, addMenuName,addMenuCode);
                        if (!_valid) {
                            $.messager.alert('提示', '菜单名称已存在或为空!', 'warning');
                            return false;
                        }
                        addFlag=false;
                        return true;
                    },
                    success : function(data) {
                        data = JSON.parse(data);
                        $.resultHandler(data, function() {
                            $('#createMenuForm').form('clear');
                            $('#createMenuDiv').dialog('close');
                        });
                        $("#searchMenuName").textbox('clear');
                        // 加载表单数据
                        menu.loadData();
                       /* $('#listDataEx1').treegrid('load', {
                            searchMenuName : ''
                        });*/
                        menu.refreshCombotree();
                        addFlag=true;
                    }
                });
        	}
        });

        // ----------------------------------------------------------------------->
        // 批量删除
        // ----------------------------------------------------------------------->
        $('#deletes').bind('click', function() {
           //var datas=$('#listDataEx1').treegrid('getData');
           //var menuIds=menu.getTreeIds(datas);
        	var datas= $('#listDataEx1').datagrid("getChecked");
        	var menuIds="";
             for(var i =0; i<datas.length;i++){
            	 menuIds += datas[i].menuId+",";
              }
           
           if(!menuIds){
               $.messager.alert('提示', '请先选中记录!', 'warning');
               return;
           }
           
           var _msg = '您确定要删除选中的记录吗?<br/><font color="red">该操作会删除菜单和旗下的所有菜单</fond>';
            $.messager.confirm('提示', _msg, function(r) {
                if (r) {
                    ajaxProcess({
                        url : getProjectUrl('/bfs/menu/drop'),
                        data : {
                            menuIds : menuIds
                        },
                        requestType : 'POST',
                        traditional : true,
                        successHandle : function(data) {
                            $.resultHandler(data, function() {
                                $('#listDataEx1').treegrid('reload');
                            });
                            menu.refreshCombotree();
                        }
                    });
                }
            });
        });
        
        // ----------------------------------------------------------------------->
        // 修改
        // ----------------------------------------------------------------------->
        // 取消
        $('#cancelEditMenu').bind('click', function() {
            $('#editMenuForm').form('clear');
            $('#editMenuDiv').window('close');
        });

        // 提交
        $('#submitEditMenu').bind('click', function() {
        	if(updateFlag){
        		updateFlag=false;
        		$('#editMenuForm').form('submit', {
                    url : getProjectUrl('/bfs/menu/edit'),
                    onSubmit : function() {
                    	updateFlag=true;
                        var _flag = $(this).form('validate');
                        if (!_flag) {
                            return false;
                        }
                        var editMenuName = $('#editMenuName').val();
                        var editMenuId = $('#editMenuId').val();
                        var editMenuCode=$('#editMenuCode').combobox('getValue');
                        var _valid = menu.validMenuName(editMenuId, editMenuName,editMenuCode);
                        if (!_valid) {
                            $.messager.alert('提示', '菜单名称已存在或为空!', 'warning');
                            return false;
                        }
                        updateFlag=false;
                        return true;
                    },
                    success : function(data) {
                        data = JSON.parse(data);
                        $.resultHandler(data, function() {
                            $('#editMenuForm').form('clear');
                            $('#editMenuDiv').dialog('close');
                        });
                        $('#listDataEx1').treegrid('reload');
                        menu.refreshCombotree();
                        updateFlag=true;
                    }
                });
        	}
        });
    },
    refreshMenuCodeCombobox:function(){
        var datas=menu.getMenuCodeData();
        menu.initMenuCodeCombobox($("#addMenuCode"),datas);
        menu.initMenuCodeCombobox($("#editMenuCode"),datas);
    },
    //获取系统类型的数据
    getMenuCodeData:function(){
        if(menu.menuCode.length!=0){
            return menu.menuCode;
        }
        ajaxProcess({
            url : getProjectUrl('/bfs/menu/getSystemType'),
            requestType : 'POST',
            async : false,
            successHandle : function(data) {
                menu.menuCode = data;
            }
        });
        return menu.menuCode;
    },
    //初始化系统编码下拉框
    initMenuCodeCombobox:function(DOM,data){
        DOM.combobox({
            valueField: 'systemType',
            textField: 'sysName',
            editable:false,
            data: data
        });
    },
    //获取用户数据
    getUserData:function(){
     var result=[];
        
        ajaxProcess({
            url:getProjectUrl('/bfs/user/combobox'),
            data:{ustatus:1},
            requestType : 'POST',
            async:false,
            successHandle : function(data) {
                result = data;
            }
        });
        
        return result;
    },
    refreshCombotree:function(){
        var datas=menu.getMenuData();
        menu.menuData=datas;
        //menu.initCombotree($("#addPId"),datas);
        //menu.initCombotree($("#editPId"),datas);
        $("#addPId").combotree({
            data:datas,
            onSelect:function(val){ 
            	if(!isEmpty(val.menuCode)){
            		$("#addMenuCode").combobox('setValue', val.menuCode);
            	}       	
            }
        });
        $("#editPId").combotree({
            data:datas,
            onSelect:function(val){ 
            	if(!isEmpty(val.menuCode)){
            		$("#editMenuCode").combobox('setValue', val.menuCode);
            	}
            }
        });
    },
    // 获取菜单树
    getMenuData:function(){
        
        var result=[];
        
        ajaxProcess({
            url:getProjectUrl('/bfs/menu/combobox'),
            requestType : 'POST',
            async:false,
            successHandle : function(data) {
                for(var i=0;i<data.rows.length;i++){
                    result.push(data.rows[i]);
                }
            }
        });
        
        return result;
    },
    // 初始化树下拉框
    initCombotree:function(DOM,data){
        
        DOM.combotree({
            data:data
        });
        
    },
    initEditCombotree:function(DOM,data){
        DOM.combotree({
            onBeforeSelect:function(node){
                var id=node.id;
                
                var editId=$("#editDeptId").val();
                if(id === editId){
                    DOM.combotree("unselect");
                }
            },
            data:data
        }); 
    },
    // -----------------------------------------------------------------------<
    // ----------------------------------------------------------------------->
    // 修改
    // ----------------------------------------------------------------------->
    openEditMenuDiv : function(id) {
       var  $node=$('#listDataEx1').treegrid('find',id);
        $('#editMenuDiv').window({
            onOpen : function() {
                menu.refreshMenuCodeCombobox();
                
                menu.menuEditData=deepClone(menu.menuData);
                
                //设置 菜单id及其子树不展示的数据
               var setSpecifiedMenuData=function(datas,id){
                    for(var i=0;i<datas.length;i++){
                        if(datas[i].id === id){
                            datas.splice(i,1);
                            continue;
                        }
                        if(datas[i].children){
                            setSpecifiedMenuData(datas[i].children,id);
                        }
                    }
                }

               setSpecifiedMenuData(menu.menuEditData,id);
               
                menu.initCombotree($("#editPId"), menu.menuEditData);
                
                $('#editMenuForm').form('load', $node);
                
                //初始化下拉框的展示。combotree的id找不到显示id
                var parantNode=$("#editPId").combotree('tree').tree('find',$node.parentId);  //寻找父节点是否存在
                if(!parantNode){//不存在
                    $("#editPId").combotree('setText', '');
                }
                if($node.parentId === ""){//选中“无上级部门 " 的数据
                    $("#editPId").combotree('setValue',' ');
                }
            }
        });
        $('#editMenuDiv').window('open');
    },
    //获取部门信息数据
    getDeptInfoData:function(deptId){
        var result;
        ajaxProcess({
          url:getProjectUrl('/bfs/dept/combobox'),
          data:{deptId:deptId},
          requestType : 'POST',
          async:false,
          successHandle : function(data) {
              result = data;
          }
        });
        return result;
    },
    // ----------------------------------------------------------------------->
    // 删除
    // ----------------------------------------------------------------------->
    openRemoveMenuDiv : function(id,parentId) {
        var  $nodes=$('#listDataEx1').treegrid('getChildren',id);
        var ids=id;
        for(var i=0;i<$nodes.length;i++){
            ids+=","+$nodes[i].id;
        }
        var _msg = '您确定要删除选中的记录吗?<br/><font color="red">该操作会删除菜单和旗下的所有菜单</fond>';
        $.messager.confirm('提示', _msg, function(r) {
            if (r) {
                ajaxProcess({
                    url : getProjectUrl('/bfs/menu/drop'),
                    requestType : 'POST',
                    traditional : true,
                    data : {
                        menuIds : ids
                    },
                    successHandle : function(data) {
                        $.resultHandler(data, function() {
                            $('#listDataEx1').treegrid('reload');
                            menu.refreshCombotree();
                        });
                    }
                });
            }
        });
    },

    // 验证菜单名称
    validMenuName : function(menuId, menuName,menuCode) {
        var _flag;
        ajaxProcess({
            url : getProjectUrl('/bfs/menu/valid'),
            requestType : 'POST',
            async:false,
            data : {
                menuId : menuId,
                menuName : menuName,
                menuCode:menuCode
            },
            successHandle : function(data) {
                _flag = data.result;
            }
        });
        return _flag;
    },
    // 初始化选择页面
    initDeptLeaderNameDiv : function() {
        $('#searchDeptLeaderName').searchbox('setValue', '');
        $('#selectDeptLeaderNameGrid').datagrid('load', {
            searchUserName : ''
        });
    },
    beforeLoad : function() {
        $('#createMenuDiv').dialog('destroy', true);
        $('#editMenuDiv').dialog('destroy', true);
    },
    loadData : function() {
    	$(".list").show();
		$(".nolist").hide();
		 var menuState=$("#searchMenuState").combobox('getValue');
         if(!isEmpty(menuState)){
             menuState=menuState.substring(menu.menuCategoryClass.length);
         }
        $('#listDataEx1').treegrid({
            url : getProjectUrl('/bfs/menu/list'),
            queryParams : {
            	 searchMenuName : $.trim($("#searchMenuName").val()),
                 searchMenuState: menuState
            },
            idField:'id',
            treeField:'text',
            columns : [ [ {
                field : 'id',
                checkbox : true
            }, {
                field : 'text',
                title : '菜单名称',
                align:'left',
                width : 200,
                formatter : function(value) {
                    return "<span title='" + value + "'>" + value + "</span>";
                }   
            }, {
                field : 'menuUrl',
                title : '菜单路径',
                width : 200,
                formatter : function(value) {
                    return "<span title='" + value + "'>" + value + "</span>";
                }   
            }, {
                field : 'menuCodeName',
                title : '菜单系统编码',
                width : 100
            },{
                field : 'mstatus',
                title : '状态',
                width : 50,
                formatter : function(value) {
                    if (value === 1) {
                        return "启用";
                    } else {
                        return "<font color='red'>停用</font>";
                    }
                }
            }, {
                field : 'control',
                title : '操作',
                width : 100,
                align : 'center',
                formatter : function(value, row) {
                	var control="";
                	if(!isEmpty(row.pid)){
                		control = '<a class="btn-edit"   style="height:24px;" name="edit" title="编辑"   href="javascript:void(0)" onclick="menu.openEditMenuDiv(\'' + row.id + '\');"></a>';
                	}                   
                    control += '<a class="btn-delete"   style="height:24px;"  name="delete" title="删除" href="javascript:void(0)" onclick="menu.openRemoveMenuDiv(\'' + row.id + '\',\'' + row.parentId + '\');"></a>';
                    return control;
                }
            } ] ],
            singleSelect : false,
            rownumbers : true,
            method : 'POST',
            fitColumns : true,
            animate : true,
            checkbox : false,
            checkOnSelect : false,
            onCheck:function(row){
                row.check=true;
                menu.checkChildNode(row.id);
            },
            onUncheck:function(row){
                row.check=false;
                menu.uncheckChildNode(row.id);
            },
            onClickRow:function(row){
                if(row.check){
                    row.check=false;
                    $("tr[node-id="+row.id+"] input[type=checkbox]")[0].checked=false;
                    menu.uncheckChildNode(row.id);
                }else{
                    row.check=true;
                   $("tr[node-id="+row.id+"] input[type=checkbox]")[0].checked=true;
                   menu.checkChildNode(row.id);
                }
            },
            onLoadSuccess : function(row,data) {
                setMenuButtonOpermission();
                
                menu.setSearchNode($('#listDataEx1'),data.rows);
                if(data.rows === null || data.rows.length === 0){
					   $(".list").hide();
					   $(".nolist").css("height", $(".list").height()).show();	 
				}
            }
        });
    },
    setSearchNode:function(DOM,datas){
        for(var i=0;i<datas.length;i++){
            if(datas[i].searchNode){
                DOM.treegrid('select',datas[i].id);
            }
            if(datas[i].children){
                menu.setSearchNode(DOM,datas[i].children);
            }
        }
    },
    checkChildNode:function(id){
        var childNode = $("#listDataEx1").treegrid('getChildren', id);             
        for (var i = 0; i < childNode.length; i++) {             
            $("tr[node-id="+childNode[i].id+"] input[type=checkbox]")[0].checked=true;
            childNode[i].check=true;
        }         
    },
    uncheckChildNode:function(id){
        var childNode = $("#listDataEx1").treegrid('getChildren', id);             
        for (var i = 0; i < childNode.length; i++) {             
            $("tr[node-id="+childNode[i].id+"] input[type=checkbox]")[0].checked=false;
            childNode[i].check=false;
        }      
    },
/*    // 获取选中的树的id.返回","分隔的字符串
    getTreeIds:function(datas){
        menu.menuTreeIds="";
       
        var treeIds=function(treeData){
            for (var i = 0; i < treeData.length; i++) {
                if(treeData[i].check){
                    menu.menuTreeIds += treeData[i].menuId+",";
                }
                treeIds(treeData[i].children);
            }
        }
       
       treeIds(datas);
        
       menu.menuTreeIds=menu.menuTreeIds.substring(0,menu.menuTreeIds.length-1);
       return menu.menuTreeIds;
    }*/
};


$(function() {
    resetSize();
    menu.init();
});
 
